<?php
namespace app\models;

use yii\db\ActiveRecord;

/**
 * 广告
 *
 * Class Ad
 * @package app\models
 *
 * @property integer $id
 * @property string $name
 * @property integer $lid
 * @property string $txt
 * @property integer $img_fid
 * @property string $url
 * @property integer $start_time
 * @property integer $end_time
 * @property integer $status
 * @property string $contact
 * @property string $email
 * @property string $mobile
 * @property integer $show
 * @property integer $click
 *
 * @property AdLocation $location 关联广告位
 * @property UploadFile $img 关联图片
 */
class Ad extends ActiveRecord
{
    const STATUS_ACTIVE = 1;
    const STATUS_STOPED = 9;
    const STATUS_DELETED = 0;

    /**
     * @inheritDoc
     */
    public function rules()
    {
        return [
            [['start_time', 'end_time'], function($attribute, $params) {
                if (!is_int($this[$attribute]) && preg_match('/^[\d- :]+$/', $this[$attribute])) {
                    $this[$attribute] = strtotime($this[$attribute]);
                }
            }],
            [['lid', 'img_fid', 'status', 'show', 'click'], 'integer'],
            [['name', 'lid', 'txt', 'url', 'start_time', 'end_time', 'status'], 'required'],
            [['name', 'txt', 'contact', 'mobile'], 'string', 'max'=>32],
            ['email', 'string', 'max'=>128],
            ['url', 'string', 'max'=>256],
            [['show', 'click'], 'default', 'value'=>0],
        ];
    }

    /**
     * 关联广告位
     * @return \yii\db\ActiveQuery
     */
    public function getLocation()
    {
        return $this->hasOne(AdLocation::className(), ['id'=>'lid']);
    }
    
    /**
     * 关联图片
     * @return \yii\db\ActiveQuery
     */
    public function getImg()
    {
        return $this->hasOne(UploadFile::className(), ['id'=>'img_fid']);
    }
    
    /**
     * 如果修改内容，判断文件是否更改
     * @inheritDoc
     */
    public function beforeSave($insert)
    {
        if (!$insert && $this->isAttributeChanged('img_fid')) {
            UploadFile::updateAll(['status'=>UploadFile::STATUS_DEL], ['id'=>$this->getOldAttribute('img_fid')]);
        }
        return parent::beforeSave($insert);
    }
    
    /**
     * 删除前先处理关联表
     * @inheritDoc
     */
    public function beforeDelete()
    {
        if ($this->img_fid > 0) {
            UploadFile::updateAll(['status'=>UploadFile::STATUS_DEL], ['id'=>$this->img_fid]);
        }
        return parent::beforeDelete();
    }
}
